package com.msk.message.service.impl;

import com.msk.common.constant.Constants;
import com.msk.common.core.redis.RedisCache;
import com.msk.common.core.smsclient.ali.AliSendSms;
import com.msk.common.utils.RandomUtil;
import com.msk.common.utils.StringUtils;
import com.msk.common.utils.spring.SpringUtils;
import com.msk.message.service.ISmsClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description 短信接口 服务层实现
 * @Author zlf
 * @Date 2023/5/9 17:03
 */
@Service
public class SmsClientServiceImpl implements ISmsClientService {

    private static final Logger log = LoggerFactory.getLogger(SmsClientServiceImpl.class);

    @Autowired
    private RedisCache redisService;

    /**
     * 阿里获取验证码
     * @param phone
     * @param type
     * @return
     */
    @Override
    public Map<String, Object> setAliPhoneCodeCache(String phone, String type) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String code = "";
            Integer EXPIRY = 60 * 5;
            //控制前端60秒内不能重复发送验证码
            Object expire = SpringUtils.getBean(RedisCache.class).getExpire(getCacheKey(phone));
            if (StringUtils.isNotNull(expire) && Integer.parseInt(expire.toString()) >= 240) {
                map.put("flag", 2);
            } else {
                String codeSub = RandomUtil.aliCodeNew();
                Map<String, String> map1 = AliSendSms.sendMessage(phone, codeSub, type);
                String isOk = map1.get("code");
                if ("OK".equals(isOk)) {
                    code = codeSub;
                    redisService.setCacheObject(getCacheKey(phone), code, EXPIRY, TimeUnit.SECONDS);
                    map.put("flag", 1);
                }
            }
        } catch (Exception e) {
            log.error(this.getClass().getName().toString() + "_" + e.getMessage(), e);
            map.put("flag", 0);
        }
        return map;
    }

    /**
     * 读取缓存中的手机验证码
     * @param phone
     * @return
     */
    @Override
    public String getPhoneCodeCache(String phone) {
        Object cacheObj = redisService.getCacheObject(getCacheKey(phone));
        if (StringUtils.isNotNull(cacheObj)) {
            return StringUtils.cast(cacheObj);
        }
        return "";
    }

    /**
     * 清除缓存中的手机验证码
     * @param phone
     */
    @Override
    public void clearPhoneCodeCache(String phone) {
        redisService.deleteObject(getCacheKey(phone));
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private static String getCacheKey(String configKey) {
        return Constants.SYS_PHONE_CODE_KEY + configKey;
    }
}
